package db

import (
	"fmt"
	"goProject/cfg"
	"runtime"
	"time"

	"gitee.com/ruige_fun/util/rdb"
	"github.com/redis/go-redis/v9"

	"gorm.io/gorm"
)

var MySQL *gorm.DB     //MySQL客户端
var MySQLData *gorm.DB //MySQL客户端

var Redis *redis.Client      //Redis客户端
var RedisToken *redis.Client //Redis客户端
var RedisData *redis.Client  //Redis客户端

var RunConfig rdb.MapString //实时动态

func init() {
	var err error
	MySQL, err = cfg.LinkMySQL(cfg.Config.MySQL.DefaultDB, cfg.Config.MySQL.LogModel, cfg.Config.MySQL.CloseAffair)
	if err != nil {
		time.Sleep(time.Second * 5)
		panic(err)
	}
	MySQLData, err = cfg.LinkMySQL(cfg.Config.MySQL.DataDB, cfg.Config.MySQL.LogModel, cfg.Config.MySQL.CloseAffair)
	if err != nil {
		time.Sleep(time.Second * 5)
		panic(err)
	}

	Redis, err = cfg.LinkRedis(cfg.Config.Redis.DefaultDB)
	if err != nil {
		time.Sleep(time.Second * 5)
		panic(err)
	}
	RedisToken, err = cfg.LinkRedis(cfg.Config.Redis.TokenDB)
	if err != nil {
		time.Sleep(time.Second * 5)
		panic(err)
	}
	RedisData, err = cfg.LinkRedis(cfg.Config.Redis.DataDB)
	if err != nil {
		time.Sleep(time.Second * 5)
		panic(err)
	}

	RunConfig = rdb.NewMapString(Redis, fmt.Sprint(cfg.Config.Main.ProjectName, "_Config"))

	go autoUpdateStatus()
}

// autoUpdateStatus 自动更新go总协程量
func autoUpdateStatus() {
	ticker := time.NewTicker(time.Second * 10)
	for {
		t := <-ticker.C
		var v = make(map[string]string)
		v["总协程量："] = fmt.Sprint(runtime.NumGoroutine())
		v["当前程序的编译时间为："] = cfg.BuildTime
		v["程序心跳时间："] = fmt.Sprint(t.Unix())
		v["监听的端口："] = fmt.Sprint(cfg.Config.Main.Port)
		_ = RunConfig.Sets(v)
	}
}
